import axios from 'axios';
import Router from 'vue-router';
import ElementUI from 'element-ui';

if(!window.Promise.prototype.finally) {
	window.Promise.prototype.finally = function (callback) {
    let P = this.constructor;
    return this.then(
        value => P.resolve(callback()).then(() => value),
        reason => P.resolve(callback()).then(() => { throw reason })
    );
	};
}

export default {
	create: function(data) {
		data.withCredentials = data.withCredentials == undefined ? true : data.withCredentials;
		let myaxios = axios.create(data);
		if(data.responseType == 'blob') {
			myaxios.interceptors.response.use( response => {
				let t_data = response.data;
				let t_data_type = t_data.type;
				if(t_data_type == 'application/vnd.ms-excel') return response;
				if(t_data_type == 'application/json') {
					var reader = new FileReader();
			    reader.addEventListener("loadend", () => {
			    	var result = '';
			    	try {
			    		result = JSON.parse(reader.result);
			    	}catch(e) {}finally{
			    		if(!result || result.s != 1) {
			    			ElementUI.Message.error(result.m || '导出操作发生错误');
			    		}
			    	}
			    });
			    reader.readAsText(t_data);
				}
			}, error => {
				ElementUI.Message.error('服务器内部错误');
			  return Promise.reject(error);
			});
		}else {
			myaxios.interceptors.response.use( response => {
				let t_data = response.data, res_config = response.config;
				if(t_data.s != 1 && res_config.url != res_config.baseURL + '/admin/isLogin' && res_config.url != res_config.baseURL + '/user/isLogin') {
					ElementUI.Message.error(t_data.m || '未知异常');
				}
			  return t_data;
			}, error => {
				ElementUI.Message.error('服务器内部错误');
			  return Promise.reject(error);
			});
		}
		
		return {
			get: (url, data = {}) => {
				return myaxios.get(url, { params:data })
			},
			post: (url, data = {}) => {
				if(!data.constructor || data.constructor.name!=='FormData') {
					data = Object.keys(data).reduce((res, key) => {
						return res += '&'+key+"="+encodeURIComponent(data[key])
					}, '').substring(1)
				}
				return myaxios.post(url, data);
			}
		}
	}
}